//
//  CubeModuleDownloaded.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-3.
//
//

#import "CubeModuleDownloaded.h"
#import "ASIHTTPRequest.h"
#import "IsolatedStorageFile+CubeLogic.h"
#import "ApiConstant+Cube.h"
#import "CubesModel.h"
#import <MainModuleSDK/DataCenter.h>
#import "CubeModule.h"
#import <chameleon-ios-sdk/CApplication.h>

@interface CubeModuleDownloaded()

-(void)eventprocess;
-(void)failed;
-(void) success;

-(void)callServerToDownload;

@end

@implementation CubeModuleDownloaded


- (void)dealloc{
    NSLog(@"CubeModuleDownloaded dealloc");
}

-(void)cancel{
    [processTimer invalidate];
    processTimer=nil;
    [request setCompletionBlock:nil];
    [request setFailedBlock:nil];
    [request cancel];
    request=nil;
}


-(void)start{
    [self cancel];
    [self callServerToDownload];
}

-(void) failed{
    [self.callback failed];
}

-(void) success{
    [self.callback unzip];

}

-(void)eventprocess{
    [processTimer invalidate];
    processTimer=nil;
    [self.callback process];
}

-(void)headersReceived:(int)contentLength{
    self.cubeModel.downloadedTotalCount=contentLength;
}

-(void)bytesReceivedBlock:(unsigned long long)size{
    self.cubeModel.downloadedProcess+=size;
    
    if(processTimer!=nil){
        return ;
    }
    
    processTimer=[NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(eventprocess) userInfo:nil repeats:NO];

}
-(void)requestComplete:(NSString*)filePath{
    [processTimer invalidate];
    processTimer=nil;
    
    [request setCompletionBlock:nil];
    [request setFailedBlock:nil];
    request=nil;
    
    BOOL _success=NO;
    const char* __path =[filePath UTF8String];
    FILE* fp=fopen(__path, "rb");
    if(fp!=nil){
        fseek(fp, 0, SEEK_END);
        long count=ftell(fp);
        fclose(fp);
        
        if(count==self.cubeModel.downloadedTotalCount){
            _success=YES;
            //success
        }
    }
    if(!_success){
        if(retryIndex<3){
            retryIndex++;
            [self callServerToDownload];
        }
        else{
            [self failed];
        }
    }
    else{
        [self success];
    }

}

-(void)requestFailed{
    [processTimer invalidate];
    processTimer=nil;
    
    [request setCompletionBlock:nil];
    [request setFailedBlock:nil];
    request=nil;

    if(retryIndex<3){
        retryIndex++;
        [self callServerToDownload];
    }
    else{
        [self failed];
    }
}

-(void)callServerToDownload{
    [self cancel];
    
    NSString* filePath=[IsolatedStorageFile cubeModelTempZip:self.cubeModel.identifier];
    

    request=[ASIHTTPRequest requestWithURL:[[ApiConstant defaultConstant] attachmentByIdURL:self.bundle accountToken:[DataCenter defaultCenter].accountToken]];
    request.timeOutSeconds=20.0f;
    request.persistentConnectionTimeoutSeconds=20.0f;
    [request setDownloadDestinationPath:filePath];
    
    __block CubeModuleDownloaded* objSelf=self;
    [request setHeadersReceivedBlock:^(NSDictionary* headers){
        [objSelf headersReceived:[[headers objectForKey:@"Content-Length"] intValue]];
    }];
    
    [request setCompletionBlock:^{
        [objSelf performSelector:@selector(requestComplete:) withObject:filePath afterDelay:0.1f];
    }];
    
    [request setFailedBlock:^{
        [objSelf performSelector:@selector(requestFailed) withObject:nil afterDelay:0.1f];
    }];
    
    [request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total) {
        
        [objSelf bytesReceivedBlock:size];
    }];
    
    
    [request startAsynchronous];

    
    
}


@end

